import React, { useState } from 'react';
import { 
  Drawer, 
  Descriptions, 
  Space, 
  Button, 
  Tabs, 
  Form, 
  Input, 
  Select, 
  Switch, 
  Avatar, 
  message,
  Divider
} from 'antd';
import { UserOutlined } from '@ant-design/icons';
import { User, AdminType, ProblemPermission, UpdateUserRequest, UpdateUserProfileRequest } from '@/types/user';
import userService from '@/services/userService';
import { InfoCard, FormCard } from '@/components/common';
import commonStyles from '@/styles/common.module.css';

const { Option } = Select;

interface UserDetailProps {
  user: User;
  visible: boolean;
  onClose: () => void;
  onUserUpdated: () => void;
}

const UserDetail: React.FC<UserDetailProps> = ({ user, visible, onClose, onUserUpdated }) => {
  const [activeTab, setActiveTab] = useState('1');
  const [userForm] = Form.useForm();
  const [profileForm] = Form.useForm();
  const [loading, setLoading] = useState(false);

  // 初始化表单值
  React.useEffect(() => {
    if (user) {
      userForm.setFieldsValue({
        username: user.username,
        email: user.email,
        admin_type: user.admin_type,
        problem_permission: user.problem_permission,
        is_disabled: user.is_disabled,
      });

      profileForm.setFieldsValue({
        real_name: user.userprofile.real_name,
        blog: user.userprofile.blog,
        mood: user.userprofile.mood,
        github: user.userprofile.github,
        school: user.userprofile.school,
        major: user.userprofile.major,
        language: user.userprofile.language,
        avatar: user.userprofile.avatar,
      });
    }
  }, [user, userForm, profileForm]);

  // 更新用户信息
  const handleUpdateUser = async (values: UpdateUserRequest) => {
    setLoading(true);
    try {
      await userService.updateUser(user.id, values);
      message.success('用户信息已更新');
      onUserUpdated();
    } catch (error) {
      console.error('Failed to update user:', error);
    } finally {
      setLoading(false);
    }
  };

  // 更新用户资料
  const handleUpdateProfile = async (values: UpdateUserProfileRequest) => {
    setLoading(true);
    try {
      await userService.updateUserProfile(user.userprofile.id, values);
      message.success('用户资料已更新');
      onUserUpdated();
    } catch (error) {
      console.error('Failed to update user profile:', error);
    } finally {
      setLoading(false);
    }
  };

  return (
    <Drawer
      title="用户详情"
      placement="right"
      width={700}
      onClose={onClose}
      open={visible}
    >
      <InfoCard
        cardType="profile"
        avatar={{
          src: userService.getAvatarUrl(user.userprofile.avatar),
          alt: user.username,
          size: 'large'
        }}
      >
        <div>
          <h2 style={{ margin: 0, fontSize: '20px' }}>{user.username}</h2>
          <p style={{ margin: '4px 0 0', color: 'var(--text-secondary)' }}>{user.email}</p>
        </div>
      </InfoCard>

      <Tabs 
        activeKey={activeTab} 
        onChange={setActiveTab}
        items={[
          {
            key: "1",
            label: "基本信息",
            children: (
              <>
                <Descriptions bordered column={1}>
                  <Descriptions.Item label="用户ID">{user.id}</Descriptions.Item>
                  <Descriptions.Item label="用户名">{user.username}</Descriptions.Item>
                  <Descriptions.Item label="电子邮箱">{user.email}</Descriptions.Item>
                  <Descriptions.Item label="用户类型">{user.admin_type}</Descriptions.Item>
                  <Descriptions.Item label="题目权限">{user.problem_permission}</Descriptions.Item>
                  <Descriptions.Item label="最后登录">
                    {user.last_login ? new Date(user.last_login).toLocaleString() : '从未登录'}
                  </Descriptions.Item>
                  <Descriptions.Item label="状态">
                    {user.is_disabled ? '禁用' : '正常'}
                  </Descriptions.Item>
                </Descriptions>

                <FormCard
                  title="编辑用户信息"
                  form={userForm}
                  onFinish={handleUpdateUser}
                  actions={[
                    <Button key="save" type="primary" htmlType="submit" loading={loading}>
                      保存更改
                    </Button>
                  ]}
                >
                  <Form.Item
                    name="admin_type"
                    label="用户类型"
                  >
                    <Select>
                      <Option value="Regular User">普通用户</Option>
                      <Option value="Admin">管理员</Option>
                      <Option value="Super Admin">超级管理员</Option>
                    </Select>
                  </Form.Item>

                  <Form.Item
                    name="problem_permission"
                    label="题目权限"
                  >
                    <Select>
                      <Option value="None">无权限</Option>
                      <Option value="Own">仅自己的题目</Option>
                      <Option value="All">所有题目</Option>
                    </Select>
                  </Form.Item>

                  <Form.Item
                    name="is_disabled"
                    label="禁用用户"
                    valuePropName="checked"
                  >
                    <Switch />
                  </Form.Item>
                </FormCard>
              </>
            )
          },
          {
            key: "2",
            label: "个人资料",
            children: (
              <>
                <Descriptions bordered column={1}>
                  <Descriptions.Item label="真实姓名">{user.userprofile.real_name || '未设置'}</Descriptions.Item>
                  <Descriptions.Item label="头像地址">{user.userprofile.avatar || '未设置'}</Descriptions.Item>
                  <Descriptions.Item label="博客">{user.userprofile.blog || '未设置'}</Descriptions.Item>
                  <Descriptions.Item label="心情">{user.userprofile.mood || '未设置'}</Descriptions.Item>
                  <Descriptions.Item label="GitHub">{user.userprofile.github || '未设置'}</Descriptions.Item>
                  <Descriptions.Item label="学校">{user.userprofile.school || '未设置'}</Descriptions.Item>
                  <Descriptions.Item label="专业">{user.userprofile.major || '未设置'}</Descriptions.Item>
                  <Descriptions.Item label="偏好语言">{user.userprofile.language || '未设置'}</Descriptions.Item>
                  <Descriptions.Item label="提交数">{user.userprofile.submission_number}</Descriptions.Item>
                  <Descriptions.Item label="通过数">{user.userprofile.accepted_number}</Descriptions.Item>
                </Descriptions>

                <FormCard
                  title="编辑用户资料"
                  form={profileForm}
                  onFinish={handleUpdateProfile}
                  actions={[
                    <Button key="save" type="primary" htmlType="submit" loading={loading}>
                      保存更改
                    </Button>
                  ]}
                >
                  <Form.Item
                    label="真实姓名"
                    name="real_name"
                  >
                    <Input placeholder="请输入真实姓名" />
                  </Form.Item>

                  <Form.Item
                    label="头像地址"
                    name="avatar"
                    tooltip="请输入头像的URL地址"
                  >
                    <Input placeholder="请输入头像URL地址" />
                  </Form.Item>

                  <Form.Item
                    label="个人博客"
                    name="blog"
                  >
                    <Input placeholder="请输入博客地址" />
                  </Form.Item>

                  <Form.Item
                    name="mood"
                    label="心情"
                  >
                    <Input placeholder="请输入心情" />
                  </Form.Item>

                  <Form.Item
                    name="github"
                    label="GitHub"
                  >
                    <Input placeholder="请输入GitHub链接" />
                  </Form.Item>

                  <Form.Item
                    name="school"
                    label="学校"
                  >
                    <Input placeholder="请输入学校" />
                  </Form.Item>

                  <Form.Item
                    name="major"
                    label="专业"
                  >
                    <Input placeholder="请输入专业" />
                  </Form.Item>

                  <Form.Item
                    name="language"
                    label="偏好语言"
                  >
                    <Input placeholder="请输入偏好编程语言" />
                  </Form.Item>
                </FormCard>
              </>
            )
          }
        ]}
      />
    </Drawer>
  );
};

export default UserDetail; 